package top.huiger.newday.utils

import android.app.Activity
import android.content.Context
import android.net.ConnectivityManager
import android.text.TextUtils
import android.util.Log
import okhttp3.Cache
import okhttp3.CacheControl
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import top.huiger.newday.App
import java.util.*

/**
 * Created by <huiGer> on 2018/1/12
</huiGer> */

class RetrofitUtils private constructor() {

    enum class BaseUrlType {
        GANK, NEWS
    }

    companion object {

        private val mContext: App = App.getAppContext()
        private var mBaseUrl = ""
        private val retrofitHashMap = HashMap<BaseUrlType, Retrofit>()

        @Synchronized
        fun getInstance(baseUrlType: BaseUrlType): Retrofit {
            if (baseUrlType == BaseUrlType.GANK) {
                mBaseUrl = "http://www.baidu.com"
            } else if (baseUrlType == BaseUrlType.NEWS) {
                mBaseUrl = "http://www.sougou.com"
            }
            loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
            Log.d("-----", "aaaaaaaaa")
            if (retrofitHashMap.containsKey(baseUrlType)) {
                Log.d("------", mBaseUrl)
                return retrofitHashMap.getValue(baseUrlType)
            } else {
                val retrofit = Retrofit.Builder()
                        .client(client.build())
                        .baseUrl(mBaseUrl)
                        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                        .build()
                retrofitHashMap.put(baseUrlType, retrofit)
                return retrofit
            }
        }

        private var loggingInterceptor = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger { message -> Log.d("====== RETROFIT ======", "Instance -> log: " + message) })

        private var cacheInterceptor: Interceptor = Interceptor { chain ->
            //拿到请求体
            var request = chain.request()
            //读接口上的@Headers里的注解配置
            var cacheControl = request.cacheControl().toString()

            //判断没有网络并且添加了@Headers注解,才使用网络缓存.
            if (!isOpenInternet(mContext) && !TextUtils.isEmpty(cacheControl)) {
                //重置请求体;
                request = request.newBuilder()
                        //强制使用缓存
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build()
            }
            //如果没有添加注解,则不缓存
            if (TextUtils.isEmpty(cacheControl) || "no-store".contains(cacheControl)) {
                //响应头设置成无缓存
                cacheControl = "no-store"
            } else if (isOpenInternet(mContext)) {
                //如果有网络,则将缓存的过期时间,设置为0,获取最新数据
                cacheControl = "public, max-age=" + 0
            } else {
                //...如果无网络,则根据@headers注解的设置进行缓存.
            }
            val response = chain.proceed(request)
            response.newBuilder()
                    .header("Cache-Control", cacheControl)
                    .removeHeader("Pragma")
                    .build()
        }

        private var client: OkHttpClient.Builder = OkHttpClient.Builder()
                //拦截log
                .addInterceptor(loggingInterceptor)
                //拦截并设置缓存
                .addNetworkInterceptor(cacheInterceptor)
                //拦截并设置缓存
                .addInterceptor(cacheInterceptor)
                .cache(Cache(mContext!!.cacheDir, (10240 * 1024).toLong()))

        /**
         * 判断网络是否打开
         *
         * @return
         */
        fun isOpenInternet(context: Context?): Boolean {
            val con = context!!.getSystemService(Activity.CONNECTIVITY_SERVICE) as ConnectivityManager
            val wifi = con.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting
            val intenter = con.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting
            return wifi || intenter
        }
    }





}
